package pers.ree.demo.concurrent;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {

    public static void main(String[] args) {
        // 5个前置任务
        CountDownLatch preCdl = new CountDownLatch(5);

        // 执行前置任务的5个线程，每个线程执行后count-1
        ExecutorService preExecutorService = Executors.newFixedThreadPool(5);
        for (int i=0; i<5; i++) {
            preExecutorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("pre thread " + Thread.currentThread().getName() + " execute begin...");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        preCdl.countDown();
                        System.out.println("pre thread " + Thread.currentThread().getName() + " countDown, count=" + preCdl.getCount());
                    }
                }
            });
        }

        // 使用3个线程同时执行后置任务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i=0; i<3; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("thread " + Thread.currentThread().getName() + " execute begin...");

                    try {
                        // 使用await阻塞，待前置任务执行完才执行
                        preCdl.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println("thread " + Thread.currentThread().getName() + " await end and executing, count=" + preCdl.getCount());
                }
            });
        }
    }

    @Test
    public void testCountDown() {
        CountDownLatch countDownLatch = new CountDownLatch(5);

        countDownLatch.countDown();

        System.out.println(countDownLatch.getCount());
    }
}
